<?php
include("../../tools/session.php");
include("../../tools/controls.php");
include("../../conf.php");
include("../../tools/pub.php");

// 如果登录失败、无权限访问，那么采取相应措施
if (!($is_login_success === true)) { session_hop_page("../index.php"); exit(); }
if (!power_check(0)) { include("tpl-inc-wp.php"); $tpl->display($oa_tpl_path . "/no-power.html"); exit(); }

/*-- 以下是实际内容 --*/
$page_status = $_POST["page_status"];
// $page_status = $_GET["page_status"];
if (!$page_status)
{
	include("tpl-inc-wp.php");
	include("../../tools/mysql.php");
	db_connect();
	
	$sql = "SELECT helpname FROM `help` WHERE deleted=0 GROUP BY helpname";
	$re = db_query($sql);
	$pagename = array();
	foreach ($re as $v)
	{
		$pagename[] = $v["helpname"];
	}
	
	$tpl->assign("pagename", $pagename);
	$tpl->display($oa_tpl_path . "/default/help.html");
}
// 显示 XML
elseif ($page_status == 1)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$helpname = $_POST["helpname"];
	
	$sql = "SELECT id, title, addtime FROM `help` WHERE deleted=0 AND helpname='" . $helpname . "'";
	$re = db_query($sql);
	
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<helps>\n";
	
	foreach ($re as $v)
	{
		echo "<item>\n";
		echo "<id>" . $v["id"] . "</id>\n";
		echo "<title><![CDATA[" . $v["title"] . "]]></title>\n";
		echo "<addtime><![CDATA[" . $v["addtime"] . "]]></addtime>\n";
		echo "</item>\n";
	}
	
	echo "</helps>\n";	
}
// 提交新的帮助
elseif ($page_status == 2)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$flag = $_POST["helpflag"];
	$name = mysql_escape_string(trim($_POST["helpname"]));
	$upid = $_POST["helpupid"];
	$title = mysql_escape_string(trim($_POST["helptitle"]));
	$content = mysql_escape_string($_POST["helpcontent"]);
	
	if ($flag == -1 || $flag == "") { if (!littletip(0)) { exit(); } }
	if ($flag == -2 && $name == "") { if (!littletip(0)) { exit(); } }
	if ($upid == "") { if (!littletip(0)) { exit(); } }
	if ($title == "") { if (!littletip(0)) { exit(); } }
	
	$helpname = ($flag == "-2") ? $name : $flag;
	
	$sql = "INSERT INTO `help`(helpname, title, content, upid, addtime)
			VALUES('" . $helpname . "', '" . $title . "', '" . $content . "', " . $upid . ", NOW())";
	$log_str = array("新增帮助“" . $title . "”成功！", "新增帮助失败！");
    echo check_status_write_to_log(db_exec($sql), $log_str, FALSE);
}
// 修改／删除页面 XML
elseif ($page_status == 3)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$helpname = $_POST["helpname"];
	
	$sql = "SELECT id, title, addtime, deleted FROM `help` WHERE helpname='" . $helpname . "'";
	$re = db_query($sql);
	
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<helps>\n";
	
	foreach ($re as $v)
	{
		echo "<item>\n";
		echo "<id>" . $v["id"] . "</id>\n";
		echo "<title><![CDATA[" . $v["title"] . "]]></title>\n";
		echo "<addtime><![CDATA[" . $v["addtime"] . "]]></addtime>\n";
		echo "<deleted>" . $v["deleted"] . "</deleted>";
		echo "</item>\n";
	}
	
	echo "</helps>\n";	
}
// 删除
elseif ($page_status == 4)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$hid = $_POST["hid"];
	$deleted = $_POST["deleted"];
	
	
	$sql = "UPDATE `help` SET deleted=" . $deleted . " WHERE id=" . $hid;
	$log_str = $deleted 
			? array("删除帮助（ID: " . $hid . "）成功！", "删除帮助失败！")
			: array("恢复帮助（ID: " . $hid . "）成功！", "恢复帮助失败！");
	echo check_status_write_to_log(db_exec($sql), $log_str, FALSE);
	
}
// 读取数据
elseif ($page_status == 5)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$hid = $_POST["hid"];
	
	$sql = "SELECT id, title, content FROM `help` WHERE id=" . $hid;
	$re = db_query_once($sql);
	
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<help>\n";
	echo "<id>" . $re["id"] . "</id>";
	echo "<title><![CDATA[" . $re["title"] . "]]></title>";
	echo "<content><![CDATA[" . $re["content"] . "]]></content>";
	echo "</help>\n";
}
// 更新数据
elseif ($page_status == 6)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$hid = $_POST["hid"];
	$title = mysql_escape_string($_POST["title"]);
	$content = mysql_escape_string($_POST["content"]);
	
	$sql = "UPDATE `help` SET title='" . $title . "', content='" . $content . "' WHERE id=" . $hid;
	$log_str = array("更新帮助（ID: " . $hid . "）的数据成功！", "更新帮助数据失败！");
	echo check_status_write_to_log(db_exec($sql), $log_str, FALSE);
}
// 更改上级位置
elseif ($page_status == 7)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$hid = $_POST["hid"];
	$upid = $_POST["upid"];
	
	$sql = "UPDATE `help` SET upid=" . $upid . " WHERE id=" . $hid;
	$log_str = array("更新帮助（ID: " . $hid . "）的上级位置成功！", "更新帮助数据失败！");
	echo check_status_write_to_log(db_exec($sql), $log_str, FALSE);
}
// 取得 helpname 和 upid 均相等的数据
elseif ($page_status == 8)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$hid = $_POST["hid"];
	$helpname = $_POST["helpname"];
	
	$sql = "SELECT id, title, squence FROM help WHERE helpname='" . $helpname . "'
			AND upid=(SELECT upid FROM help WHERE id=" . $hid . ") ORDER BY addtime ASC";
	$re = db_query($sql);
	
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<helps>\n";
	
	foreach ($re as $v)
	{
		echo "<item>\n";
		echo "<id>" . $v["id"] . "</id>";
		echo "<title><![CDATA[" . $v["title"] . "]]></title>";
		echo "<squence>" . $v["squence"] . "</squence>";
		echo "</item>\n";
	}
	
	echo "</helps>\n";
}
// 更新帮助的次序
elseif ($page_status == 9)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$squence = unescape_string($_POST["squence"]);
	$s = json_decode($squence); 
	
	$flag = TRUE;
	foreach ($s as $k => $v)
	{
		$sql = "UPDATE `help` SET squence=" . $v . " WHERE id=" . $k;
		$flag = $flag && db_exec($sql);
	}
	$log_str = array("更新帮助文档条列次序成功！", "更新帮助文档条列次序失败！");
	echo check_status_write_to_log($flag, $log_str, FALSE);
	
}
// 生成 XML 文件
elseif ($page_status == 10)
{
	include("../../tools/mysql.php");
	db_connect();
	
	$xmlstruct = array();
	
	$sql = "SELECT helpname, id, title, content, upid FROM `help` WHERE deleted=0 ORDER BY upid, squence, addtime ASC";
	$re = db_query($sql);
	
	foreach ($re as $v)
	{
		$tmpArray = array("title" => $v["title"],
				"content" => $v["content"],
				"children" => array()
			);
		if ($v["upid"] == 0)
		{
			// $xmlstruct[$v["helpname"]] = array();
			if (empty($xmlstruct[$v["helpname"]]) || !is_array($xmlstruct[$v["helpname"]]))
			{ $xmlstruct[$v["helpname"]] = array(); }
			$xmlstruct[$v["helpname"]][$v["id"]] = $tmpArray;
		}
		else
		{
			search_id_position($xmlstruct[$v["helpname"]], $v["upid"], $v["id"], $tmpArray);
		}
	}
	
	// print_r($xmlstruct);
	// echo json_encode($xmlstruct);
	// exit();
	
	$flag = false;
	foreach ($xmlstruct as $k => $v)
	{
		$filename = "../help/xmls/" . $k . ".xml";
		if (!$handle = fopen($filename, "w"))
		{
			echo "Error: 不能打开文件！";
			exit();
		};
		$str = '<?xml version="1.0" encoding="utf-8"?>';
		$str .= "\n<helproot>\n";
		$str .= "<name><![CDATA[" . $k . "]]></name>\n";
		$str .= produce_xml_fragment($v, 1);
		$str .= "</helproot>\n";
		
		if (fwrite($handle, $str)) { $flag = true; };
		fclose($handle);
	}
	
	$log_str = array("生成帮助文档 XML 文件成功！", "生成帮助文档 XML 文件失败！");
	echo check_status_write_to_log($flag, $log_str, FALSE);
	
}

// 小提示程序
function littletip($f)
{
	if ($f) { echo "Success: 提交成功！"; return true; }
	else { echo "Error: 提交失败！"; return false; }
}

// 从结构中搜索上指 ID 的位置（*** 关键！！！）
function search_id_position(&$s, $upid, $id, $data)
{
	$rtn = false;
	if (!empty($s)) {
		foreach ($s as $k => $v)
		{
			if ($k == $upid) {
				$s[$k]["children"][$id] = $data;
				$rtn = true;
				break;
			}	
			else
			{
				if (!empty($s[$k]["children"]))
				{
					if (search_id_position($s[$k]["children"], $upid, $id, $data)) {
						$rtn = true;
						break;
					}
				}
			}
		}
	}
	return $rtn;
}

// 生成片段 XML 字符串
function produce_xml_fragment($s, $l)
{
	$temp = "";
	if (!empty($s)) {
		foreach ($s as $k => $v)
		{
			$temp .= "<help_" . $l . ">\n";
			$temp .= "<id_" . $l . ">" . $k . "</id_" . $l . ">\n";
			$temp .= "<title_" . $l . "><![CDATA[" . $v["title"] . "]]></title_" . $l . ">\n";
			$temp .= "<content_" . $l . "><![CDATA[" . $v["content"] . "]]></content_" . $l . ">\n";
			$temp .= "<children_" . $l . ">" . produce_xml_fragment($v["children"], ($l + 1)) . "</children_" . $l . ">\n";
			$temp .= "</help_" . $l . ">\n";
		}
	}
	return $temp;
}
?>
